#!/usr/bin/python2.4
#
# Copyright 2008 Google Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.


"""spiral's datastore reset module.

This is spiral reset tool (admin only) that is used to delete records or reset
the database. It is hard to use due to GAE quota limits.
"""

__author__ = 'stratus@google.com (Gustavo Franco)'

import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.ext import webapp
import package


class Removal(webapp.RequestHandler):
  """Spiral's removal class."""

  def get(self):
    """Parses a removal GET request through HTTP.

    When you call get() and there is all and kind set it query for and delete
    all records in the given kind, otherwise you must call get setting number
    kind and dist (ie: hardy) to point out what will be deleted.
    """
    kind = self.request.get('kind')
    all = self.request.get('all')
    number = int(self.request.get('number'))
    dist = self.request.get('dist')
    if all and kind:
      results = db.GqlQuery('SELECT * FROM :1', kind)
      for result in results:
        self.response.out.write('Removing %s %s (%s) from db<br/>'
                                % (result.name, result.version, result.dist))
        result.delete()

    elif number and kind and dist:
      results = db.GqlQuery('SELECT * FROM :1 where dist = :2', kind, dist)

      for index in range(number):
        self.response.out.write('Removing %s %s (%s) from db<br/>' %
                                (results[index].name,
                                 results[index].version,
                                 results[index].dist))
        results[index].delete()

    else:
      self.response.out.write('Not enough parameters, you are admin fix ya!')


def main():
  application = webapp.WSGIApplication([('/.*', Removal)], debug=True)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
